<template>
    <div class="page">
        <div style="margin-bottom: 20px"><Button v-show="hasButtonPermission('101010307')" @click="openDutyPermissionModal">修改职能数据权限</Button></div>
        <Card>
            <Tree style="margin-left: 30px" :data="dutyTree" :render="renderTree"></Tree>
        </Card>
        <SetDutyPermission @dutyPermissionSelected="dutyPermissionSelected"></SetDutyPermission>
    </div>
</template>

<script type="text/ecmascript-6">
    import * as dutyOpr from '../../http/duty.api'
    import SetDutyPermission from './setDutyPermission.vue'

    export default {
        components: {
            SetDutyPermission
        },
        data () {
            return {
                selNode: null,  // 已选中 的树 节点
                dutyTree: [{
                    title: '全部职能',
                    expand: true,
                    origin: {id: null, status: '1'},
                    children: []
                }],
                buttonProps: {
                    type: 'ghost',
                    size: 'small',
                },
            }
        },
        mounted() {
            this.getDutyList(); // 初始化组织架构树
        },
        watch: {
            selNode: function (newVal, oldVal) {
                // this.getEmployees();
                this.$store.commit('duty/setSelectedDuty', newVal&&newVal.node.origin)
            }
        },
        methods: {
            hasButtonPermission(permission) {
                return this.$store.getters['login/hasButtonPermission'](permission);
            },
            renderTree (h, { root, node, data }) {
                const _this = this;
                let opr1 = [
                    _this.hasButtonPermission('101010301') && h('Button', {
                        props: { ...this.buttonProps, ...{ icon: 'ios-plus-empty', type: 'primary'}},
                        on: { click: () => { this.addDuty(root, node, data) } }
                    })||''
                ];
                let opr2 = [
                    h('ButtonGroup', {}, [
                        _this.hasButtonPermission('101010301') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'ios-plus-empty'}},
                            on: {
                                click: () => { this.addDuty(root, node, data) }
                            }
                        }),
                        _this.hasButtonPermission('101010305') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'edit'}},
                            on: {
                                click: () => { this.editDuty(root, node, data) }
                            }
                        }),
                        _this.hasButtonPermission('101010304') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'ios-copy'}},
                            on: {
                                click: () => { this.copyDuty(root, node, data) }
                            }
                        }),
                        _this.hasButtonPermission('101010308') && h('Button', {
                            props: { ...this.buttonProps, ...{ icon: 'ios-minus-empty'}},
                            on: {
                                click: () => { this.deleteDuty(root, node, data) }
                            }
                        })
                    ])
                ];
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%',
                        lineHeight: '24px',
                        height: '24px'
                    }
                }, [
                    h('span', {
                        on: {
                            click: function() {
                                // console.log(root, node, data)
                                _this.selNode = (_this.selNode === node) ? null: node;
                            }
                        }}, [
                        h('Icon', {
                            props: {
                                type: (data.children&&data.children.length)&&'ios-folder-outline'||'ios-paper-outline'
                            },
                            style: {
                                marginRight: '8px'
                            }
                        }),
                        h('span',{class: { 'ivu-tree-title': true, 'ivu-tree-title-selected': _this.selNode === node }},
                            !data.origin.status ? [h('Badge',{props: {dot: true}}, [h('span',{on:{ mouseover: () => _this.$Message.warning(`${data.title} 被禁用`) }}, data.title)])] : data.title)
                    ]),
                    h('span', {
                        style: {
                            display: (_this.selNode === node)&&'inline-block'||'none',
                            // float: 'right',
                            marginLeft: '5px'
                        }
                    }, (data.origin.id===null)&&opr1||opr2)
                ]);
            },
            addDuty (root, node, data) { // 新增 部门
                const _self = this;
                let parentNode = node;
                let arr = [data.title];
                while(parentNode = root.find(el => el.nodeKey === parentNode.parent)) {
                    arr.unshift(parentNode.node.title);
                }
                let tips = `当前操作提示：${arr.join(' | ')} 添加下级`
                const args = {
                    funcName: '', //职能名称
                    status: '1', //职能状态
                    funcDesc: '', //职能描述'
                    parentId: data.origin.id, //父id
                };
                _self.editDutyModal(Object.assign({}, args, {status: (args.status==="1")&&true||false}), tips, (args) => {
                    if (!args.funcName) {
                        return _self.$Message.warning('请输入职能名称');
                    }
                    // 调用 添加接口
                    dutyOpr.addDuty(args).then(function (res) {
                        // console.log(res)
                        // 刷新
                        _self.getDutyList();
                    }).catch(function (err) {
                        _self.$Message.warning('添加失败:'+err.data.message);
                    });
                })
            },
            editDutyModal(args, tips, okFn) {
                const _self = this;
                _self.$Modal.confirm({
                    title: '新增/编辑/复制职能',
                    render: (h) => {
                        return h('div', {
                            style: {
                                // marginTop: '30px'
                            },
                        }, [
                            h('div', {
                                style: {
                                    marginTop: '15px',
                                    color: 'red'
                                },
                                props: {
                                },
                            },[tips]),
                            h('Input', {
                                style: {
                                    marginTop: '15px'
                                },
                                props: {
                                    value: args.funcName,
                                    autofocus: true,
                                    placeholder: '请输入职能名称.'
                                },
                                on: {
                                    input: (val) => {
                                        args.funcName = val;
                                    }
                                }
                            }),
                            h('Input', {
                                style: {
                                    marginTop: '15px'
                                },
                                props: {
                                    value: args.funcDesc,
                                    autofocus: true,
                                    placeholder: '请输入职能描述.'
                                },
                                on: {
                                    input: (val) => {
                                        args.funcDesc = val;
                                    }
                                }
                            }),
                            h('Select', {
                                style: {
                                    marginTop: '15px'
                                },
                                props: {
                                    value: args.status===true&&'1'||args.status===false&&'0',
                                    autofocus: true,
                                    placeholder: '请选择状态'
                                },
                                on: {
                                    'on-change': (val) => {
                                        args.status = val;
                                    }
                                }
                            }, [
                                h('Option', {
                                    props: { value: '1', label: '正常'},
                                }),
                                h('Option', {
                                    props: { value: '0', label: '禁用'},
                                })
                            ])
                        ])
                    },
                    okText: '保存',
                    onOk: () => {okFn(args)},
                    onCancel: () => {}
                })
            },
            editDuty (root, node, data){
                const _self = this;
                let parentNode = node;
                let arr = [data.title];
                while(parentNode = root.find(el => el.nodeKey === parentNode.parent)) {
                    arr.unshift(parentNode.node.title);
                }

                const args = {
                    "funcName": data.origin.funcName, // 职能
                    "funcDesc": data.origin.funcDesc, // 职能描述
                    "parentId": data.origin.parentId, // 当前组织id
                    "status": data.origin.status&&"1"||"0" // 状态 1 正常 0 禁用
                };
                let tips = `当前操作提示：${arr.join(' | ')} 编辑`
                // 查询 当前节点信息
                dutyOpr.getDutyInfo(data.origin.id).then(function (res) {
                    // console.log(res.data.result)
                    _self.editDutyModal(Object.assign({}, args, {status: (args.status==="1")&&true||false}), tips, (args) => {
                        // 调用 添加接口
                        // console.log(args)
                        dutyOpr.updateDuty(data.origin.id, args).then(function (res) {
                            // 刷新
                            _self.getDutyList();
                        });
                    })
                }).catch(function (err) {
                    _self.$Message.warning('修改失败:'+err.data.message);
                });
            },
            copyDuty (root, node, data){
                const _self = this;
                let parentNode = node;
                let arr = [data.title];
                while(parentNode = root.find(el => el.nodeKey === parentNode.parent)) {
                    arr.unshift(parentNode.node.title);
                }
                // console.log(data.origin.status)
                const args = {
                    "funcName": data.origin.funcName+'_copy', // 职能
                    "funcDesc": data.origin.funcDesc, // 职能描述
                    "parentId": data.origin.parentId, // 当前组织id
                    "status": data.origin.status&&"1"||"0" // 状态 normal正常 forbidden禁用
                };
                let tips = `当前操作提示：${arr.join(' | ')} 复制`

                _self.$Modal.confirm({
                    title: '确认',
                    content: `<div><p style="color: red">${tips}</p>
                                <p>确定复制吗？</p>
                            </div>`,
                    onOk: () => {
                        dutyOpr.copyDuty(data.origin.id).then(function (res) {
                            _self.$Message.info('复制成功');
                            // 刷新
                            _self.getDutyList();
                        }).catch(function (err) {
                            // console.log(err)
                            _self.$Message.error('复制失败：'+err.data.message);
                        });
                    },
                    onCancel: () => {
                        _self.$Message.info('取消');
                    }
                });
            },
            deleteDuty (root, node, data) {
                const _self = this;
                let str = node.children&&node.children.length ? `当前节点含有 ${node.children&&node.children.length||0} 个子节点` : '';
                _self.$Modal.confirm({
                    title: '删除确认',
                    content: `<div><p>${str}</p>
                                <p>确定删除吗？</p>
                            </div>`,
                    onOk: () => {
                        const parentKey = root.find(el => el === node).parent;
                        const parent = root.find(el => el.nodeKey === parentKey).node;
                        // 删除 组织机构节点
                        dutyOpr.deleteDuty(data.origin.id).then(function (res) {
                            const index = parent.children.indexOf(data);
                            parent.children.splice(index, 1);
                            _self.$Message.info('删除成功');

                            // 清空选中节点
                            _self.selNode = null;
                        }).catch(function (err) {
                            // console.log(err)
                            _self.$Message.warning(err.data.message);
                        });
                    },
                    onCancel: () => {
                        _self.$Message.info('取消');
                    }
                });
            },
            getDutyList() { // 获取所有组织架构
                const _this = this;
                dutyOpr.getDutyList().then(function (res) {
                    let groupsObj = res.data.rows.reduce(function(groups, item) {
                        let val = (''+item['parentId']).toUpperCase();
                        groups[val] = groups[val] || [];
                        groups[val].push(item);
                        return groups;
                    }, {});
                    function buildTree(node) {
                        let obj = {
                            title: node.funcName,
                            expand: true,
                            origin: node
                        };
                        if (groupsObj[node.id]) { // 有下级节点
                            // 设置子节点，进行监听
                            _this.$set(obj, 'children', groupsObj[node.id].map(item => buildTree(item)));
                        }
                        return obj;
                    }
                    // 找根节点，可能调整
                    _this.dutyTree[0].children = res.data.rows.filter(item => item.parentId === null).map(node => buildTree(node))
                }).catch(function () {
                    console.log(arguments);
                });
            },
            openDutyPermissionModal() {
                const _this = this;
                if (!_this.selNode) {
                    return _this.$Message.warning('请先选择 要修改的职能');
                }
                _this.$store.commit('duty/toggleShowModal', true)
            },
            dutyPermissionSelected(items) {
                dutyOpr.addDutyPermission(this.selNode.node.origin.id, {dataPermissions: items.map(item => ({permissionType: item.type, permissionCode: item.code}))})
            }
        },
    }
</script>
<style scoped>

</style>
